//
//  MasterViewController.m
//  BaoGongBao
//
//  Created by User on 14/11/4.
//  Copyright (c) 2014年 irule. All rights reserved.
//

#import "MasterViewController.h"
#import "DetailViewController.h"

@interface MasterViewController ()
{
	BOOL mbSearched;
}

@end

@implementation MasterViewController

- (void)awakeFromNib {
	if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
	    self.clearsSelectionOnViewWillAppear = NO;
	    self.preferredContentSize = CGSizeMake(320.0, 600.0);
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	switch (alertView.tag)
	{
		case kAlertViewTag_isRegister:
		{
			switch (buttonIndex)
			{
				case 0:
				{
					exit(0);
				}
					break;
				case 1:
				{
					_gifImageView.hidden = YES;
					RegisterViewController *vc = [[RegisterViewController alloc] initWithNibName:nil bundle:nil];
					UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:vc];
                    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:@"0x552cb"]];
                    [[UINavigationBar appearance]setTintColor:[UIColor whiteColor]];
					[self.navigationController presentViewController:nc animated:YES completion:nil];
				}
					break;
				default:
				{
				}
					break;
					
			}
		}
			break;

		default:
		{
		}
			break;

	}
}

- (void)startLogin
{

	NSDictionary *dictionary = @{@"appid"		: kSys_appid,
								 @"deviceid"	: kSys_deviceid,//[OpenUDID value],
								 @"userName"	: @"",//account,
								 @"loginplace"	: gloginplace
								 };
	[[NetWorkRequestApi sharedNetWorkRequestApi] nrLogin:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"%@", responseObject);
		switch ([[responseObject objectForKey:@"Tag"] integerValue]) {
			case 1:
			{
				[[iToast makeText:[responseObject objectForKey:@"Message"]] show];
				gUserInfo = responseObject;
				gToken = [responseObject objectForKey:@"Token"];

				switch (gDataStore.mStartPageType) {
					case kStartPageType_SpareParts:
					{
						_gifImageView.hidden = YES;
						BaoGongDanViewController *vc = [[BaoGongDanViewController alloc] initWithNibName:nil bundle:nil];
						vc.title = @"零部件报工";
						vc.mBaoGongDanViewControllerType = kBaoGongDanViewControllerType_SpareParts;
						[self.navigationController pushViewController:vc animated:YES];
					}
						break;

					case kStartPageType_Merchandiser:
					{

						_gifImageView.hidden = YES;
						BaoGongDanViewController *vc = [[BaoGongDanViewController alloc] initWithNibName:nil bundle:nil];
						vc.title = @"跟单报工";
						vc.mBaoGongDanViewControllerType = kBaoGongDanViewControllerType_Merchandiser;
						[self.navigationController pushViewController:vc animated:YES];
					}
						break;

					default:
                    {
                        _gifImageView.hidden = YES;
//                        BaoGongDanViewController *vc = [[BaoGongDanViewController alloc] initWithNibName:nil bundle:nil];
//                        vc.title = @"跟单报工";
//                        vc.mBaoGongDanViewControllerType = kBaoGongDanViewControllerType_Merchandiser;
//                        [self.navigationController pushViewController:vc animated:YES];
                    }
						break;
				}
			}
				break;
			case 2:
			{
				UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:[responseObject objectForKey:@"Message"] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
				alertView.tag = kAlertViewTag_isRegister;
				[alertView show];
			}
				break;
			default:
				break;
		}
	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

		[[iToast makeText:kNRStr_LoadDataFailure] show];
	}];

}

- (void)rightBarButtonItemSelector:(id)sender
{

	SettingTableViewController *vc = [[SettingTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
	[self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - Utility
- (void)clearMapView
{
	self.mapView.showsUserLocation = NO;

	[self.mapView removeAnnotations:self.mapView.annotations];

	[self.mapView removeOverlays:self.mapView.overlays];

	self.mapView.delegate = nil;
}

- (void)clearSearch
{
	self.search.delegate = nil;
}

#pragma mark - Handle Action

- (void)returnAction
{
	[self.navigationController popViewControllerAnimated:YES];

	[self clearMapView];

	[self clearSearch];
}

#pragma mark - AMapSearchDelegate

- (void)searchRequest:(id)request didFailWithError:(NSError *)error
{
	NSLog(@"%s: searchRequest = %@, errInfo= %@", __func__, [request class], error);

	m_hub.detailsLabelText = @"查询地址失败";
	[m_hub hide:YES afterDelay:3];
}

#pragma mark - Initialization

- (void)initMapView
{
	self.mapView = [[MAMapView alloc] initWithFrame:self.view.bounds];
	self.mapView.frame = self.view.bounds;

	self.mapView.delegate = self;

	self.mapView.visibleMapRect = MAMapRectMake(220880104, 101476980, 272496, 466656);
}

- (void)initSearch
{
	self.search = [[AMapSearchAPI alloc] initWithSearchKey:[MAMapServices sharedServices].apiKey Delegate:nil];
	self.search.delegate = self;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
	if (updatingLocation) {
		m_hub.detailsLabelText = @"正在查询地址...";
		AMapReGeocodeSearchRequest *request = [[AMapReGeocodeSearchRequest alloc] init];

		request.location = [AMapGeoPoint locationWithLatitude:userLocation.coordinate.latitude longitude:userLocation.coordinate.longitude];
		request.requireExtension = YES;

		[self.search AMapReGoecodeSearch:request];
	}
}


- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
	m_hub.detailsLabelText = @"定位失败";
	[m_hub hide:YES afterDelay:3];
	[self startLogin];
}

/*!
 @brief 逆地理编码查询回调函数
 @param request 发起查询的查询选项(具体字段参考AMapReGeocodeSearchRequest类中的定义)
 @param response 查询结果(具体字段参考AMapReGeocodeSearchResponse类中的定义)
 */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
	if (!mbSearched) {

		[m_hub hide:YES];
		mbSearched = YES;
		NSLog(@"%@", response.regeocode.formattedAddress);
		gloginplace = [NSString stringWithFormat:@"%@,%f,%f", response.regeocode.formattedAddress, request.location.longitude, request.location.latitude];

		[self startLogin];
	}
}


- (void)initObservers
{
	/* Add observer for showsUserLocation. */
	[self.mapView addObserver:self forKeyPath:@"showsUserLocation" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];


	[self initObservers];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
//	self.navigationItem.leftBarButtonItem = self.editButtonItem;

	UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
	lbTitle.textColor = [UIColor whiteColor];
	lbTitle.textAlignment = NSTextAlignmentCenter;
	lbTitle.text = @"报工宝";
	self.navigationItem.titleView = lbTitle;
	[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHexString:@"0x0552cb"]];
	[[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

	[self initMapView];

	[self initSearch];
	self.mapView.showsUserLocation = YES;
	self.mapView.userTrackingMode = MAUserTrackingModeNone;

	//版本更新
	NSString * urlHostString = [NSString stringWithFormat:@"%@/api/App/GetVersion?appId=HMP_002&platform=%@&deviceId=%@",kURLmain, kSys_PlatForm, kSys_deviceid];

	AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
	[manager GET:urlHostString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
		NSLog(@"%@", responseObject);
		NSString *localVersion =[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
		if (![localVersion isEqualToString:[responseObject objectForKey:@"Version"]]) {
			NSString * url = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=https://mip.helichina.com:%@/setup/ios/HMP_002/%@",UPPORT,[responseObject objectForKey:@"DownloadUrl"]];

			NSURL * urlApp = [NSURL URLWithString:url];
			[[UIApplication sharedApplication] openURL:urlApp];

			return ;
		}
		gDataStore = [DataStore sharedDataStore];
//		[self startLogin];

	} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
		NSLog(@"%@", error);
	}];



	UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"setting"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemSelector:)];
	addButton.tintColor = nil;
	self.navigationItem.rightBarButtonItem = addButton;
	self.detailViewController = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];

	NSString* filePath = [[NSBundle mainBundle] pathForResource:@"welcome1.gif" ofType:nil];
	NSData* imageData = [NSData dataWithContentsOfFile:filePath];

	_gifImageView = [[SCGIFImageView alloc] initWithFrame:self.navigationController.view.frame];
	[_gifImageView setData:imageData];

	[self.navigationController.view addSubview:_gifImageView];
	_gifImageView.hidden = NO;

	m_hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
	m_hub.detailsLabelText = @"正在定位...";
	[m_hub show:YES];
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)insertNewObject:(id)sender {
	NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
	NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
	NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
	    
	// If appropriate, configure the new managed object.
	// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
	[newManagedObject setValue:[NSDate date] forKey:@"timeStamp"];
	    
	// Save the context.
	NSError *error = nil;
	if (![context save:&error]) {
	    // Replace this implementation with code to handle the error appropriately.
	    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
	    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
	    abort();
	}
}

#pragma mark - Segues

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//	if ([[segue identifier] isEqualToString:@"showDetail"]) {
//	    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
//	    NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
//	    DetailViewController *controller = (DetailViewController *)[[segue destinationViewController] topViewController];
//	    [controller setDetailItem:object];
//	    controller.navigationItem.leftBarButtonItem = self.splitViewController.displayModeButtonItem;
//	    controller.navigationItem.leftItemsSupplementBackButton = YES;
//	}
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
//	return [[self.fetchedResultsController sections] count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//	id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
//	return [sectionInfo numberOfObjects];
	return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 180;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
	return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"banner_home"]];
	return imageView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//	[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:[NSString stringWithFormat:@"Cell%ld", (long) indexPath.row]];

//	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:@"Cell%ld", (long)indexPath.row] forIndexPath:indexPath];

	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

	cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	switch (indexPath.row)
	{
		case 0:
		{
			cell.textLabel.text = @"零部件报工";
			UIImageView *v = (UIImageView *)[cell viewWithTag:11];
			if (!v) {
				v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"lbjbg"]];
				v.backgroundColor = [UIColor colorWithHexString:@"0x929292"];
				v.frame = CGRectMake(8, 8, 44, 44);
				[cell addSubview:v];
			}

		}
			break;

		case 1:
		{
			cell.textLabel.text = @"跟单报工";
			UIImageView *v = (UIImageView *)[cell viewWithTag:12];
			if (!v) {
				v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gdbg"]];
				v.backgroundColor = [UIColor colorWithHexString:@"0x7e6b5a"];
				v.frame = CGRectMake(8, 8, 44, 44);
				[cell addSubview:v];
			}
		}
			break;

		case 2:
		{
			cell.textLabel.text = @"报工统计";
			UIImageView *v = (UIImageView *)[cell viewWithTag:13];
			if (!v) {
				v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bgtj"]];
				v.backgroundColor = [UIColor colorWithHexString:@"0x51795d"];
				v.frame = CGRectMake(8, 8, 44, 44);
				[cell addSubview:v];
			}

		}
			break;
case 3:
		{
			cell.textLabel.text = @"新闻中心";
			UIImageView *v = (UIImageView *)[cell viewWithTag:14];
			if (!v) {
				UIImage *image = [UIImage imageNamed:@"news"];
				v = [[UIImageView alloc] initWithImage:image];
				v.backgroundColor = [UIColor colorWithHexString:@"0x795158"];
				v.frame = CGRectMake(8, 8, 44, 44);
				[cell addSubview:v];
			}
		}
			break;
		default:
		{
			return nil;
		}
			break;
			
	}

	cell.indentationWidth = 60;
	cell.textLabel.font = [UIFont systemFontOfSize:17];
	return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
	// Return NO if you do not want the specified item to be editable.
	return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	switch (indexPath.row)
	{
		case 0:
		{
			BaoGongDanViewController *vc = [[BaoGongDanViewController alloc] initWithNibName:nil bundle:nil];

			UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
			lbTitle.textColor = [UIColor whiteColor];
			lbTitle.textAlignment = NSTextAlignmentCenter;
			lbTitle.text = cell.textLabel.text;
			vc.navigationItem.titleView = lbTitle;
			vc.mBaoGongDanViewControllerType = kBaoGongDanViewControllerType_SpareParts;
			[self.navigationController pushViewController:vc animated:YES];
		}
			break;
		case 1:
		{
			BaoGongDanViewController *vc = [[BaoGongDanViewController alloc] initWithNibName:nil bundle:nil];

			UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
			lbTitle.textColor = [UIColor whiteColor];
			lbTitle.textAlignment = NSTextAlignmentCenter;
			lbTitle.text = cell.textLabel.text;
			vc.navigationItem.titleView = lbTitle;
			vc.mBaoGongDanViewControllerType = kBaoGongDanViewControllerType_Merchandiser;
			[self.navigationController pushViewController:vc animated:YES];
		}
			break;
		default:
		{
		}
			break;
			
	}
}

#pragma mark - Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController
{
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];
    
    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
    NSArray *sortDescriptors = @[sortDescriptor];
    
    [fetchRequest setSortDescriptors:sortDescriptors];
    
    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Master"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;
    
	NSError *error = nil;
	if (![self.fetchedResultsController performFetch:&error]) {
	     // Replace this implementation with code to handle the error appropriately.
	     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
	    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
	    abort();
	}
    
    return _fetchedResultsController;
}    

//- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
//{
//    [self.tableView beginUpdates];
//}

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        default:
            return;
    }
}

//- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
//       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
//      newIndexPath:(NSIndexPath *)newIndexPath
//{
//    UITableView *tableView = self.tableView;
//    
//    switch(type) {
//        case NSFetchedResultsChangeInsert:
//            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//            break;
//            
//        case NSFetchedResultsChangeDelete:
//            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//            break;
//            
//        case NSFetchedResultsChangeUpdate:
//            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
//            break;
//            
//        case NSFetchedResultsChangeMove:
//            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//            [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
//            break;
//    }
//}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}

/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. 
 
 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    // In the simplest, most efficient, case, reload the table view.
    [self.tableView reloadData];
}
 */

@end
